package com.kxf.checkapksoplugin.util

import com.kxf.checkapksoplugin.CheckApkSoPlugin
import org.codehaus.groovy.runtime.ProcessGroovyMethods
import java.io.File
import java.util.concurrent.TimeUnit

object CommandUtils {

    fun gradlewCommand(taskName: String,
                       configurationName: String,
                       dependencyName: String,
                       workingDir: File = File(".")): String?{
        if (CheckApkSoPlugin.logFlag){
            println("gradlewCommand taskName==>>${taskName}")
            println("gradlewCommand configurationName==>>${configurationName}")
            println("gradlewCommand dependencyName==>>${dependencyName}")
        }
        var cmd = arrayListOf(
            taskName,"--configuration",configurationName,"--dependency",dependencyName
        )
        if (System.getProperty("os.name").lowercase().contains("windows")) {
            cmd.add(0, "gradlew")
            cmd.add(0, "/c")
            cmd.add(0, "cmd")
            return runCommand(cmd, workingDir)
        }else{
            var re = try {
                cmd.add(0, "../gradlew")
                ProcessGroovyMethods.getText(ProcessGroovyMethods.execute(cmd))
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
            return re
        }
    }

    /**
     * 调用系统命令行中的命令.以List<String>的方式输入命令的各个参数.
     * 命令执行完毕后会以String?传回结果,不会在终端显示
     * 默认在当前目录中执行,超时时间为60秒
     */
    fun runCommand(
        cmd: ArrayList<String>,
        workingDir: File = File("."),
        timeoutAmount: Long = 60L,
        timeUnit: TimeUnit = TimeUnit.SECONDS
    ): String? = runCatching {
        ProcessBuilder(cmd)
            .directory(workingDir)
            .redirectErrorStream(true)
            .start().also { it.waitFor(timeoutAmount, timeUnit) }
// jdk17之后这样写
//            .inputReader().readText()
// jdk17之前这样写
            .inputStream.bufferedReader().readText()
    }.onFailure {
        println("runCommand erro==>>")
        it.printStackTrace()
    }.getOrNull()
}